package org.hardcode.rpc.codec;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import org.hardcode.rpc.common.utils.SerializationUtils;
import org.hardcode.rpc.protocol.RpcProtocol;
import org.hardcode.rpc.protocol.header.RpcHeader;
import org.hardcode.rpc.serialization.api.Serialization;

public class RpcEncoder extends MessageToByteEncoder<RpcProtocol<Object>>
implements  RpcCodec{

    /**
     * 预留了对于 序列化 和反序列功能的扩展点
     * @param ctx
     * @param msg
     * @param byteBuf
     * @throws Exception
     */
    @Override
    protected void encode(ChannelHandlerContext ctx,
                          RpcProtocol<Object> msg, ByteBuf byteBuf) throws Exception {

        RpcHeader header = msg.getHeader();
        byteBuf.writeShort(header.getMagic());
        byteBuf.writeByte(header.getMsgType());
        byteBuf.writeByte(header.getStatus());
        byteBuf.writeLong(header.getRequestId());

        //序列化类型
        String  serializationType = header.getSerializationType();

        //Serialization扩展点
        Serialization  serialization = getJdkSerialization();

        byteBuf.writeBytes(SerializationUtils.paddingString(serializationType).getBytes("UTF-8"));

        byte[] data = serialization.serialize(msg.getBody());
        byteBuf.writeInt(data.length);
        byteBuf.writeBytes(data);
    }
}
